<?php

namespace app\admin\controller\dorm;

use app\common\controller\Backend;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorImage;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Behavior extends Backend
{
    /**
     * @var \app\common\model\Behavior
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['typeList', 'categoryList', 'cxCategoryList'];
    protected $excludeFields = [];
    protected $schoolLimit = true;
    protected $modelValidate = true;
    protected $relationSearch = true;

    protected $categoryType = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
    protected $typeData = [];
    protected $imageData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Behavior');

        $this->typeData = \app\common\model\Behavior::$typeList;
        $this->view->assign('typeData', $this->typeData);

        $images = BehaviorImage::all();
        foreach ($images as $key => $datum) {
            if (strstr($datum['url'], '/uploads/')) {
                $images[$key]['url'] = config('app_url') . $datum['url'];
            }
        }
        $this->imageData = $images;
        $this->view->assign('imageData', $this->imageData);

        $categoryTypeData = [
            BehaviorCategory::DORM => BehaviorCategory::$typeList[BehaviorCategory::DORM],
            BehaviorCategory::DORM_STUDENT => BehaviorCategory::$typeList[BehaviorCategory::DORM_STUDENT],
        ];
        $this->view->assign('categoryTypeData', $categoryTypeData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('behavior')
                ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = behavior.category_id')
                ->where($where)
                ->whereIn('category.type', $this->categoryType)
                ->count();

            $list = $this->model
                ->alias('behavior')
                ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = behavior.category_id')
                ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id', 'left')
                ->where($where)
                ->whereIn('category.type', $this->categoryType)
                ->field('behavior.*,category.name category_name,category.type category_type,image.url image_url')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['type_text'])->toArray();
                $school_ids = array_column($list, 'school_id');

                if ($school_ids) {
                    $school_ids = array_unique($school_ids);
                    $schools = \app\common\library\Client::instance()->schoolProfile($school_ids);
                    if ($schools) {
                        foreach ($list as $key => $value) {
                            if (isset($schools[$value['school_id']])) {
                                $list[$key]['school_name'] = $schools[$value['school_id']]['name'];
                            }
                        }
                    }
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (!in_array($params['behavior_category_type'], $this->categoryType)) {
                    $this->error(__('数据错误'));
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if ($this->schoolLimit && $this->schoolLimitFieldAutoFill) {
                    $params[$this->schoolLimitField] = $this->auth->school_id;
                }
                $result = false;
                Db::startTrans();
                try {

                    $category = BehaviorCategory::where('school_id', $params['school_id'])
                        ->where('type', $params['behavior_category_type'])
                        ->find();

                    if (!$category) {
                        //$name = BehaviorCategory::$typeList[$params['behavior_category_type']];
                        //$type = $params['behavior_category_type'];
                        //$category = BehaviorCategory::add($name, $type, $this->auth->school_id);

                        $category = new BehaviorCategory();
                        $category->name = BehaviorCategory::$typeList[$params['behavior_category_type']];
                        $category->type = $params['behavior_category_type'];
                        $category->school_id = $this->auth->school_id;
                        $category->is_deduct = 0;
                        $category->save();
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['category_id'] = $category->id;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->with('category')->where('id', $ids)->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();
        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if ($row['category']) {
                        if ($params['behavior_category_type'] != $row['category']['type']) {
                            $category = BehaviorCategory::where('school_id', $params['school_id'])
                                ->where('type', $params['behavior_category_type'])
                                ->find();
                            if (!$category) {
                                $name = BehaviorCategory::$typeList[$params['behavior_category_type']];
                                $type = $params['behavior_category_type'];
                                $category = BehaviorCategory::add($name, $type, $this->auth->school_id);
                            }

                            $params['category_id'] = $category->id;
                        } else {
                            $params['category_id'] = $row['category_id'];
                        }
                    } else {
                        $name = BehaviorCategory::$typeList[$params['behavior_category_type']];
                        $type = $params['behavior_category_type'];
                        $category = BehaviorCategory::add($name, $type, $this->auth->school_id);
                        $params['category_id'] = $category->id;
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 类型列表
     *
     * @User ZhenZiHan
     * @Date 2020/1/1
     *
     */
    public function typeList()
    {
        $result = $this->typeData;

        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['id' => $key, 'name' => $value];
        }
        $data = ['searchlist' => $searchList];
        $this->success('', null, $data);
    }

    /**
     * 分类列表
     *
     * @User ZhenZiHan
     * @Date 2020/1/1
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function categoryList()
    {
        $type = $this->request->request('type');
        $result = BehaviorCategory::where('type', $type)->order('sort', 'asc')->select();
        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['id' => $value['id'], 'name' => $value['name']];
        }
        $data = ['searchlist' => $searchList];
        $this->success('', null, $data);
    }

    public function cxCategoryList()
    {
        $school_id = $this->request->request('school_id', 0);
        $result = BehaviorCategory::where('school_id', $school_id)
            ->whereIn('type', $this->categoryType)
            ->order('sort', 'asc')
            ->select();
        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['value' => $value['id'], 'name' => $value['name']];
        }
        $this->success('', null, $searchList);
    }
}
